import pymysql
from config.yaml_config import GetConf


class MysqlOperate:
    def __init__(self):
        mysql_conf = GetConf().get_mysql_config()
        self.host = mysql_conf["host"]
        self.db = mysql_conf["db"]
        self.port = mysql_conf["port"]
        self.user = mysql_conf["user"]
        self.password = mysql_conf["password"]
        self.conn = None  # 数据库连接对象
        self.cur = None  # 游标对象

    def __conn_db(self):  # 双下划线表示私有方法
        try:
            self.conn = pymysql.connect(
                host=self.host,
                user=self.user,
                passwd=self.password,
                db=self.db,
                port=self.port,
                charset="utf8",
            )
        except Exception as e:
            print(e)
            return False
        self.cur = self.conn.cursor()
        return True

    def __close_conn(self):
        self.cur.close()
        self.conn.close()
        return True

    def __commit(self):
        self.conn.commit()
        return True

    def query(self, sql):
        try:
            self.__conn_db()
            self.cur.execute(sql)
            query_data = self.cur.fetchall()
            if not query_data:
                query_data = None
                print("没有获取到数据，表为空")
            return query_data
        except Exception as e:
            print(f"查询失败: {e}")
            raise
        finally:
            self.__close_conn()

    def execute(self, sql, return_rows=False, success_msg=None):
        """
        执行SQL语句（插入、更新、删除）

        :param sql: SQL语句
        :param return_rows: 是否返回受影响行数
        :param success_msg: 成功时的提示信息（包含{rows}占位符）
        :return: 受影响行数（如果return_rows=True）
        """
        try:
            self.__conn_db()
            self.cur.execute(sql)
            self.__commit()
            rows_affected = self.cur.rowcount
            if success_msg:
                print(success_msg.format(rows=rows_affected))
            return rows_affected if return_rows else None
        except Exception as e:
            print(f"执行失败: {e}")
            self.conn.rollback()
            raise
        finally:
            self.__close_conn()


if __name__ == '__main__':
    mysql_operate = MysqlOperate()
    # results = mysql_operate.query("select * from student")
    # for row in results:
    #     print(row)
    rows = mysql_operate.execute("INSERT INTO student (id, name, age) VALUES (6, '张三', 20) ",True,"添加成功")
    print(rows)
